package com.zj.study.controller;

import com.alibaba.excel.EasyExcel;
import com.zj.study.configuration.EasyExcelSetting;
import com.zj.study.configuration.FileModel;
import com.zj.study.pojo.User;
import com.zj.study.utils.OssTemplate;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 赵赳
 * @since 2021/8/25 12:00
 */
@RestController
@Slf4j
public class UploadController {

  private final OssTemplate ossTemplate;

  @Autowired
  public UploadController(OssTemplate ossTemplate) {
    this.ossTemplate = ossTemplate;
  }

  /**
   * 图片上传
   *
   * @param fileModel 图片模型
   * @return 图片访问地址
   */
  @PostMapping("/uploadFile")
  public String uploadFile(@RequestBody FileModel fileModel) {
    return ossTemplate.uploadFile(fileModel.getFilePath(), fileModel.getFileName());
  }

  /**
   * 上传excel文件
   *
   * @return 文件地址
   * @throws IOException IO异常
   */
  @PostMapping("/uploadExcel")
  public String uploadExcel() throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    var data = getData();
    log.info("报表导出Size: " + data.size() + "条。");
    String filename = "订单导出文件.xlsx";

    // 设置格式
    EasyExcel.write(os, User.class)
        .registerWriteHandler(EasyExcelSetting.formatExcel())
        .registerWriteHandler(new EasyExcelSetting.ExcelWidthStyleStrategy())
        .sheet("订单导出数据")
        .doWrite(data);

    byte[] content = os.toByteArray();
    InputStream is = new ByteArrayInputStream(content);
    return ossTemplate.uploadFile2Cos(filename, is);
  }

  private List<User> getData() {
    return List.of(
        new User("1", "张三1", 28, "123@qq.com"),
        new User("2", "张三2", 28, "123@qq.com"),
        new User("3", "张三3", 28, "123@qq.com"),
        new User("4", "张三4", 28, "123@qq.com"),
        new User("5", "张三5", 28, "123@qq.com")
    );
  }

}
